package opl.services;

import java.lang.reflect.Type;
import java.util.List;
import java.util.TimerTask;

import opl.dal.DataAccess;
import opl.entities.NotificationDetails;
import opl.ui.NotificationsActivity;
import opl.ui.R;
import opl.utilities.NetworkHelper;
import opl.utilities.RestServiceExecuter;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class NotificationTimerTask extends TimerTask {

	private static final String NOTIFICATION_URL = "http://oplwcf.joymononline.co.in/OPLService.svc/getnotifications";
	private static final String LATESTNOTIFICATION_URL="http://oplwcf.joymononline.co.in/OPLService.svc/getlatestnotifications?count=%s&lowerlimit=%s";
	// Joy : Seems the localhost doesnt work with android.May be 127.0.0.1 or
	// the current ip? How to test :-(
	// Eldhose : You can use the ip : 10.0.2.2 which will points to localhost.
	// private static final String NOTIFICATION_URL =
	// "http://localhost/OPLService/OPLService.svc/getnotifications";
	private Context _context;
	private static int notificationTimer;
	private long INTERVAL = 2 * 60 * 1000;

	public NotificationTimerTask(Context context, long interval) {
		_context = context;
		notificationTimer = 0;
		INTERVAL = interval;
	}

	@Override
	public void run() {
		
		try {
		//ProcessUsingGetNotificationsService();
			ProcessUsingGetLatestNotificationService();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void ProcessUsingGetLatestNotificationService() throws Exception{

		String jsonNotifications;
		if (NetworkHelper.isInternetAvailable(_context)) {
			String fullUrl = String.format(LATESTNOTIFICATION_URL, String.valueOf(3),getLatestNotificationId());
			Log.i("OPL", String.format("Fetching notification using auto : %s", fullUrl));
			jsonNotifications = RestServiceExecuter
					.getUrlContentResultAsString(fullUrl);
			Type collectionType = new TypeToken<List<NotificationDetails>>() {
			}.getType();
			List<NotificationDetails> fixtures = new Gson().fromJson(
					jsonNotifications, collectionType);
			Log.i("OPL", String.format("Received notifications : %s",String.valueOf( fixtures.size())));
			// Joy - Expected notifications / 2 mins is max 3 .
			// So Show all the notifications till the time when we get more
			// than 10 notifications / 2 mins.
			for (int i = 0; i < fixtures.size(); i++) {
				NotificationDetails detail = fixtures.get(i);
				insertToDatabase(detail);
				showNotification(detail.getCaption(),
						detail.getDescription());
			}
			/*if (fixtures.size() > 0) { showNotification("OPL",
			  "You have " + fixtures.size() + " new OPL Notification(s)");
			  } */
		}
	}

	private void ProcessUsingGetNotificationsService() throws Exception {
		String jsonNotifications;
		if (NetworkHelper.isInternetAvailable(_context)) {
			String fullUrl = NOTIFICATION_URL + "?dateAsElapsedMS="
					+ String.valueOf(System.currentTimeMillis())
					+ "&interval=" + INTERVAL;
			jsonNotifications = RestServiceExecuter
					.getUrlContentResultAsString(fullUrl);
			// Joy - No idea why this is here ???
			// Eldhose : Since our current implementation is not a service
			// we need to fetch its content like this.
			// Once we move to WCF, we can use the below method.
			// jsonNotifications =
			// RestServiceExecuter.Execute(fullUrl,MethodType.GET, "");
			Type collectionType = new TypeToken<List<NotificationDetails>>() {
			}.getType();
			List<NotificationDetails> fixtures = new Gson().fromJson(
					jsonNotifications, collectionType);

			// Joy - Expected notifications / 2 mins is max 3 .
			// So Show all the notifications till the time when we get more
			// than 10 notifications / 2 mins.
			for (int i = 0; i < fixtures.size(); i++) {
				NotificationDetails detail = fixtures.get(i);
				insertToDatabase(detail);
				showNotification(detail.getCaption(),
						detail.getDescription());
			}
			/*
			 * if (fixtures.size() > 0) { showNotification("OPL",
			 * "You have " + fixtures.size() + " new OPL Notification(s)");
			 * }
			 */
		}
	}

	private void insertToDatabase(NotificationDetails fixture) {
		DataAccess da = new DataAccess(_context);
		NotificationDetails detail = fixture;
		da.addNotification(detail);
		da.close();
		Log.i("OPL",String.format("Interted Notification to DB : %s-%s", detail.getId(), detail.getCaption())) ;
	}
private int getLatestNotificationId(){
	DataAccess da=new DataAccess(_context);
	NotificationDetails lstNotifications=da.getLatestNotificationDetails();
	if(lstNotifications ==null)  
	return 0;
	else return lstNotifications.getId();
}
	private void showNotification(String caption, String desc) {
		NotificationManager notificationManager = (NotificationManager) _context
				.getApplicationContext().getSystemService(
						Context.NOTIFICATION_SERVICE);

		CharSequence notiText = desc;
		long time = System.currentTimeMillis();

		Notification notification = new Notification(R.drawable.icon, notiText,
				time);
		Intent notificationIntent = new Intent(_context,
				NotificationsActivity.class);
		notificationIntent.setAction("actionstring"
				+ System.currentTimeMillis());
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		PendingIntent contentIntent = PendingIntent.getActivity(_context, 0,
				notificationIntent, 0);

		notification.setLatestEventInfo(_context, caption, desc, contentIntent);
		notificationManager.notify(notificationTimer++, notification);
	}

}
